package com.ld.xuanKe.controller;

import com.alibaba.excel.EasyExcel;
import com.ld.xuanKe.entity.User;
import com.ld.xuanKe.listener.MyUploadUserDataListener;
import com.ld.xuanKe.service.UserService;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.captcha.utils.CaptchaUtil;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ProjectName xuanKe
 * @ClassName UserAction
 * @Author 刘邓
 * @Date 2023-12-09 8:27
 */
@Controller
@Scope("prototype")
public class UserAction implements ModelDriven<User> {
	private User user;
	@Resource
	private UserService userService;

	//excel模板下载
	private InputStream inputStream;
	private String filename;
	//导入excel
	private File uploadFile;
	private String uploadFileFileName;

	public User getModel() {
		user = new User();
		return user;
	}

	//	获取验证码
	public void checkCode() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			CaptchaUtil.out(request, response);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public String login() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		if (user.getPassword() == null) {
			session.setAttribute("error", "密码为空");
			return "login-fail";
		} else if (user.getAccount() == null) {
			session.setAttribute("error", "账号为空");
			return "login-fail";
		}
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		String verCode = request.getParameter("verCode");
		if (!CaptchaUtil.ver(verCode, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			request.setAttribute("error", "验证码错误");
			return "login-fail";
		}
		User user1 = userService.login(user.getAccount(), user.getPassword());
		if (user1 == null) {
			session.setAttribute("error", "账号或者密码错误");
			return "login-fail";
		} else {
			session.setAttribute("user", user1);
			if (user1.getStatus() == 0) {
				return "login-user";
			} else {
				return "login-admin";
			}
		}
	}

	public String register() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if (user.getPassword() == null) {
			request.setAttribute("error", "密码为空");
			return "register-fail";
		} else if (user.getAccount() == null) {
			request.setAttribute("error", "账号为空");
			return "register-fail";
		} else if (user.getUsername() == null) {
			request.setAttribute("error", "用户名为空");
			return "register-fail";
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		String verCode = request.getParameter("verCode");
		if (!CaptchaUtil.ver(verCode, request)) {
			CaptchaUtil.clear(request);  // 清除session中的验证码
			request.setAttribute("error", "验证码错误");
			return "register-fail";
		}
		if (userService.getUserByAccount(user.getAccount()) != null) {
			request.setAttribute("error", "该用户已存在");
			return "register-fail";
		}
		int register = userService.register(user);
		if (register == 0) {
			session.setAttribute("error", "注册失败");
			return "register-fail";
		} else {
			return login();
		}


	}

	public String add() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if (userService.getUserByAccount(user.getAccount()) != null) {
			request.setAttribute("message", "该用户已存在");
			return "user-add";
		}
		user.setStatus(0);
		int add = userService.add(user);
		if (add == 1) {
			session.setAttribute("message", "添加成功");
		} else {
			session.setAttribute("message", "添加失败");
		}
		return "user-add";
	}

	public String update() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String account = (String) session.getAttribute("account");
		if (!user.getAccount().equals(account) && userService.getUserByAccount(user.getAccount()) != null) {
			request.setAttribute("message", "该用户已存在");
			return "user-update";
		}
		int update = userService.update(user);
		if (update == 1) {
			session.setAttribute("message", "更新成功");
		} else {
			session.setAttribute("message", "更新失败");
		}
		return "user-update";
	}

	public String delete() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		System.out.println(user.getId());
		int delete = userService.delete(user.getId());
		if (delete == 1) {
			session.setAttribute("message", "删除成功");
		} else {
			session.setAttribute("message", "删除失败");
		}
		return "user-delete";
	}

	//导出excel
	public void downLoadUsers() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			HttpServletResponse resp = ServletActionContext.getResponse();
			List<User> users = userService.list();
			resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			resp.setCharacterEncoding("utf-8");
			// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
			String fileName = URLEncoder.encode("学生信息", "UTF-8").replaceAll("\\+", "%20");
			resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			EasyExcel.write(resp.getOutputStream(), User.class).sheet("学生信息").doWrite(users);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	//	模板下载
	public String excelTemplate() {
		return "success";
	}

	public InputStream getInputStream() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			String filePath = "/home/upload/studentTemplate.xlsx";
			inputStream = new FileInputStream(ServletActionContext.getRequest().getServletContext().getRealPath(filePath));
			return inputStream;
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	//导入excel
	public String importExcel() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			if (uploadFile == null) {
				session.setAttribute("message", "导入失败");
				return "user-import";
			}
			EasyExcel.read(new FileInputStream(uploadFile), User.class, new MyUploadUserDataListener()).sheet().doRead();
			session.setAttribute("message", "导入成功");
			return "user-import";
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}
}
